package com.ogj.service;

import com.alibaba.fastjson.JSON;
import com.ogj.pojo.Content;
import com.ogj.utils.HtmlParseUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//业务编写
@Service
public class ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private HtmlParseUtils htmlParseUtils;


    //1、解析数据，放入到es 索引中
    public Boolean parseContent(String keywords) throws IOException {
        List<Content> contentList = htmlParseUtils.parseJDKey(keywords);
        //list插入到es索引库
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i=0;i<contentList.size();i++) {
            bulkRequest.add(new IndexRequest("jd_goods")
            .source(JSON.toJSONString(contentList.get(i)),XContentType.JSON));
        }
        BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !responses.hasFailures();
    }


    //2、获取这些数据
    public List<Map<String,Object>> searchPage(String keywords,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }

        //条件搜索
        SearchRequest searchResult = new SearchRequest("jd_goods");

        SearchSourceBuilder builder = new SearchSourceBuilder();
        //分页
        builder.from(pageNo);
        builder.size(pageSize);
        //精准匹配关键字
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keywords);
        builder.query(termQueryBuilder);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        searchResult.source(builder);
        SearchResponse response = restHighLevelClient.search(searchResult, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> mapList = new ArrayList<>();
        for (SearchHit documentFields : response.getHits().getHits()) {
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            mapList.add(sourceAsMap);
        }
        return mapList;
    }



    //3、获取这些数据 实现高亮功能
    public List<Map<String,Object>> searchPageHighlight(String keywords,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }

        //条件搜索
        SearchRequest searchResult = new SearchRequest("jd_goods");

        SearchSourceBuilder builder = new SearchSourceBuilder();
        //分页
        builder.from(pageNo);
        builder.size(pageSize);
        //精准匹配关键字
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keywords);
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", keywords);


        builder.query(matchQuery);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //构建高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false); //关闭多个高亮显示
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        builder.highlighter(highlightBuilder);

        //执行搜索
        searchResult.source(builder);
        SearchResponse response = restHighLevelClient.search(searchResult, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> mapList = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            //解析高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            //获取初始的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //置换高亮字段
            if(title!=null){
                Text[] fragments = title.fragments();
                //将高亮字段替换之前未高亮字段
                String new_title = "";
                for (Text fragment : fragments) {
                    new_title += fragment;
                }
                sourceAsMap.put("title",new_title); //替换
            }
            mapList.add(sourceAsMap);
        }
        return mapList;
    }

}
